/**
 * 采购经理审批
 */
import * as React from 'react'
import { Card, Button, Form, Row, Col, Cascader, Input, Checkbox, message,Select,Icon } from 'antd'
import Authentication from '../../router/Authentication'
import { PageHeaderLayout, CardTable } from '../../components'
import { post, SUBMIT_MANAGER_APPROVAL } from '../../service/api'
import '../../assets/style/TableList.less'
const FormItem = Form.Item
const Option=Select.Option
export interface State {
  formValues: any
  pagination: any
  selectedRows: any []
  allSelected: boolean
  expandForm: boolean
}

@Authentication
class ManagerApproval extends React.Component<any, State> {
  
  state = {
    pagination: {
      pageIndex: 1,
      pageSize: '20'
    },
    formValues: {},
    selectedRows: [],
    allSelected: false,
    expandForm: false
  }
  componentDidMount () {
    this.search(1)
  }

  handleFormReset = () => {
    const { form } = this.props
    form.resetFields()
    this.search(1)
  }
  //选中事件
  handleSelectRows = (rows: any []) => {
    const { list } = this.props
    let allSelected = false
    if(rows.length>0 && rows.length == list.length) allSelected = true
    this.setState({
      allSelected,
      selectedRows: rows,
    })
  }
  /**
   * 点击查询按钮
   */
  handleSearch = (e: any) => {
    e.preventDefault()
    const { form } = this.props
    form.validateFields((err: any, fieldsValue: any) => {
      if (err) return
      this.search(1, fieldsValue)
    })
  }
  /**
   * 调用查询方法,1是查询，2是loadmore
   */
  search (type: number, param?: any) {
    const { getList } = this.props
    const { formValues } = this.state
    let params = {}
    if (type == 1) {
      const pagination = {
        pageIndex: 1,
        pageSize: '20'
      }
      this.setState({
        ...this.state,
        formValues: param || {},
        pagination
      })
      params = { ...pagination, ...param }
    } else {//加载更多
      params = { ...param, ...formValues }
    }
    getList(type, params)
  }
  toggleForm = () => {
    const { expandForm } = this.state
    this.setState({
      expandForm: !expandForm,
    })
  }
  renderSimpleForm() {
    const { form, categorys, status,venders } = this.props
    const { getFieldDecorator } = form
    const { expandForm } = this.state
    getFieldDecorator('dlid', { initialValue: [] })
    getFieldDecorator('xlid', { initialValue: [] })
    getFieldDecorator('status', { initialValue: [] })
    getFieldDecorator('flag', { initialValue: [] })
    const changeCateGorys = (e: string []) => {
      let dlid = e[0]
      let xlid = ''
      if (e.length>1) xlid = e[1]
      form.setFieldsValue({
        dlid,
        xlid
      })
    }
    const changeStatus = (e: string []) => {
      let status = e[0]
      let flag = ''
      if (e.length>1) flag = e[1]
      form.setFieldsValue({
        status,
        flag
      })
    }
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={5} sm={24}>
            <FormItem label="编码">
              {getFieldDecorator('sampleid')(
                <Input placeholder="请输入编码"/>
              )}
            </FormItem>
          </Col>
          <Col md={5} sm={24}>
            <FormItem label="波段">
              {getFieldDecorator('band')(
                <Input placeholder="请输入波段"/>
              )}
            </FormItem>
          </Col>
          <Col md={5} sm={24}>
            <FormItem label="分类">
              <Cascader options={categorys} onChange = {changeCateGorys} changeOnSelect placeholder="请选择分类"/>
            </FormItem>
          </Col>
          <Col md={4} sm={24}>
            <span className="submitButtons">
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>  
                {expandForm?
                  <span> 收起 <Icon type="up" /></span>:
                  <span>展开 <Icon type="down" /></span>
                }
              </a>
            </span>
          </Col>
        </Row>
        {expandForm&&(<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={5} sm={24}>
            <FormItem label="状态">
              <Cascader options={status} onChange = {changeStatus} changeOnSelect placeholder="请选择状态"/>
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="供应商">
              {getFieldDecorator('suppliers')(
              <Select placeholder="请选择供应商" allowClear showSearch>
                {venders.map( (vender: any, index: number) => (<Option key={index} value={vender.Key}>{vender.Value}</Option>))}
              </Select>)}
            </FormItem>
          </Col>
        </Row>)}
      </Form>
    )
  }
  /**
   * 加载更多
   */
  onLoadMore = () => {
    const { pagination: { pageIndex, pageSize } } = this.state
    let pagination = {
      pageIndex: pageIndex+1,
      pageSize
    }
    this.setState({
      pagination,
    })
    this.search(2, pagination)
  }
  //编辑
  handleInfo = (row: any) => {
    const { record } = this.props
    record({ id: row.sampleid, no: row.id })
    this.props.history.push({ pathname: '/mgnsp/detail' })
  }
  //全选和取消
  handleChangeAll = (flag: boolean) => {
    let rows: any [] = []
    if(flag) {
      const { list } = this.props
      list.map((row: any) => {
          rows = [...rows, row.sampleid]
      })
    } 
    this.setState({
      allSelected: flag,
      selectedRows: rows
    })
  }
  handleSubmit = (mask: number) => {
    const { selectedRows } = this.state
    post(SUBMIT_MANAGER_APPROVAL, {
      ids: selectedRows.join(','),
      mask
    }).then((res: any) => {
      if (res.code == '1') {
        message.success('操作成功！')
        this.setState({
          allSelected: false,
          selectedRows: []  
        })
        this.search(1)
      }else {
        message.error(res.errMsg)
      }
    })
  }
  render () {
    const { loading, list } = this.props
    const { selectedRows, allSelected } = this.state
    return (
      <PageHeaderLayout>
        <Card bordered={false}>
          <div className="tableList">
            <div className="tableListForm">{this.renderSimpleForm()}</div>
            <div className="tableListOperator">
              <Checkbox checked={allSelected} onChange={(e: any) => this.handleChangeAll(e.target.checked)}>全选</Checkbox>
              {selectedRows.length > 0 && (
                <span>
                  <Button type="danger" onClick={() => this.handleSubmit(0)}>未审核</Button>
                  <Button type="primary" onClick={() => this.handleSubmit(1)}>通过</Button>
                  <Button type="danger" onClick={() => this.handleSubmit(2)}>不通过</Button>
                  <Button onClick={() => this.handleSubmit(3)}>驳回</Button>
                  <Button onClick={() => this.handleChangeAll(false)}>取消</Button>
                </span>
              )}
            </div>
            <CardTable
              selectedRows = {selectedRows}
              picKey = 'img1'
              textRow = "baseflag"
              rowKey = "id"
              select = {true}
              loading={loading}
              data={list}
              onLoadMore={this.onLoadMore}
              onClick = {this.handleInfo}
              onSelectRow={this.handleSelectRows}
            />
          </div>
        </Card>
      </PageHeaderLayout>
    )
  }
}

export default Form.create()(ManagerApproval)